<template>
  <div>
    <div class="options">
      <el-scrollbar ref="viewScrollbar" @scroll="handleScroll"
                    :style="{height:(maxHeight -160) + 'px'}">
        <el-row :gutter="24" justify="space-between">
          <el-col :xl="6" :lg="6" :md="24" :sm="24" :xs="24">
            <div class="file-box">
              <div class="upload" @click="handleEditView">
                <div class="icon">
                  <el-icon :size="44">
                    <Plus />
                  </el-icon>
                  <div><span>导入3D场景</span></div>
                  <div><span style="font-size: 10px;">3D模型编辑：导入、修改、材质、光照、动画、导出、实时预览、协作分享</span></div>
                </div>
              </div>
            </div>
          </el-col>
          <el-col :xl="6" :lg="6" :md="24" :sm="24" :xs="24"
            v-for="view in page.list"
            @contextmenu.prevent="e=>onContextmenu(e, view)"
            :key="view.id"
          >
            <el-card body-class="" class="image-card">
              <div>
                <div style="padding: 5px;" v-if="view.content">
                  <el-image v-if="!view.vi" style="border-radius: 5px;"
                            draggable="false"
                            @click.prevent="handleView(view)"
                            class="el-img"
                            :src="view.icon"
                            :title="'点击查看3D'"
                            fit="cover"
                  />
                  <div v-else class="container" style="height: 256px; border-radius: 5px;">
                    <div v-html="view.content"></div>
                  </div>
                </div>
                <div v-else style="padding: 5px;">
                  <el-image style="border-radius: 5px;"
                            draggable="false"
                            class="el-img"
                            :src="view.icon"
                            :title="view.name"
                            fit="cover"
                  />
                </div>
              </div>
              <div style="display: flex;justify-content: center;">
                <div v-if="!view.vi" style="text-align: center;">{{view.name}}</div>
                <div v-if="view.vi" style="text-align: center; margin-left: 10px;">
                  <el-button type="primary" @click="handleDoubleClickView(view)">放大</el-button>
                  <el-button @click="handleEditView(view)">编辑</el-button>
                  <el-button @click="handleDeleteView(view)">删除</el-button>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-scrollbar>
    </div>
  </div>
  <!-- 右键菜单 -->
  <right-context-menu :rightMenuPositon="rightMenuPositon"
                      @onDelete="handleDeleteView"
                      @onEdit="handleEditView"
  />
  <el-dialog
    title="3D模型编辑"
    v-model="showDialog"
    fullscreen
    append-to-body
    destroy-on-close
  >
    <div style="position: relative;" :style="{minHeight: height}">
      <ContentWrap :bodyStyle="{ padding: '0px' }" class="!mb-0">
        <IFrame :src="threeSrc"/>
      </ContentWrap>
    </div>

    <template #footer>
      <el-button @click="showDialog = false">取 消</el-button>
    </template>
  </el-dialog>

  <el-dialog
    title="3D模型查看"
    v-model="showDialog2"
    fullscreen
    append-to-body
    destroy-on-close
  >
    <div v-html="threeContent"></div>

    <template #footer>
      <el-button @click="showDialog2 = false">取 消</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ViewApi } from "@/api/threed";
import RightContextMenu from "@/components/RightContextMenu/index.vue";
import {Plus} from "@element-plus/icons-vue";

const threeUrl = import.meta.env.VITE_3D_URL;
const showDialog = ref(false)
const showDialog2 = ref(false)
const threeSrc = ref('')
const height = ref('500px')
const threeContent = ref('')
/** 编辑按钮操作 */
const handleEditView = (view) => {
  if(view && view.modelId){
    threeSrc.value = threeUrl + "/edit?id=" + view.modelId;
  }else{
    threeSrc.value = threeUrl;
  }
  window.parentFunction = parentFunction;
  showDialog.value = true
}

const parentFunction = async () =>{
  console.log('parentFunction')
  await getList({})
}
/** 预览按钮操作 */
const handleView = (view) => {
  page.value.list.forEach(v => {
    v.vi = false;
  })
  view.vi = true
}

/** 预览按钮操作 */
const handleDoubleClickView = (view) => {
  const newWidth = '100%';
  const newHeight = (window.innerHeight - 130) + 'px';
  // 使用正则表达式匹配并替换 width 和 height 的值
  let str = view.content;
  str = str.replace(/width="\d+"/, `width="${newWidth}"`);
  str = str.replace(/height="\d+"/, `height="${newHeight}"`);
  threeContent.value = str;
  showDialog2.value = true
}

/** 查询列表 */
const page = ref({
  pageNo: 1,
  pageSize: 10,
  list: [],
  total: 0,
})

const viewScrollbar = ref(null);
const handleScroll = () => {
  if (viewScrollbar.value) {
    const wrap = viewScrollbar.value.wrapRef;
    const tolerance = 10; // 容差值，可以根据需要调整
    // 检查是否滚动到底部
    //console.log(wrap.clientHeight + wrap.scrollTop, wrap.scrollHeight)
    if (wrap.clientHeight + wrap.scrollTop >= wrap.scrollHeight - tolerance) {
      console.log('到达底部');
      // 在这里处理到达底部的逻辑
      page.value.pageNo += 1;
      //console.log(Math.ceil(page.value.total / page.value.pageSize))
      if(page.value.pageNo > Math.ceil(page.value.total / page.value.pageSize)){
        return;
      }
      //console.log(page.value.pageNo, page.value.pageSize, page.value.total)
      getList({
        'pageNo': page.value.pageNo,
        'pageSize': page.value.pageSize,
      })
    }
  }
};
const getList = async (pageParam) => {
  try {
    //无分页参数，则查询第一页
    if(!pageParam || !pageParam.pageNo || !pageParam.pageSize){
      page.value.list = []
    }
    // 执行查询
    const response = await ViewApi.getViewPage({
      'pageNo': pageParam?pageParam.pageNo: 1,
      'pageSize': pageParam?pageParam.pageSize: 20,
    });
    const list = response.list;
    const total = response.total;
    if(list && list.length){
      page.value.list.push(...list);
      page.value.total = total;
    }

  } catch (error) {
    console.error('查询3d场景数据失败:', error);
    return { list: [], total: 0 };
  }
}

const handleDeleteView = async (view) => {
  ElMessageBox.confirm('是否删除3d场景？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await ViewApi.deleteView(view.id)
    ElMessage.success("删除3d场景成功");
    await getList({})
  })
}
const rightMenuPositon = ref({});
// 鼠标右键事件
const onContextmenu = (e,view) => {
  rightMenuPositon.value = {
    x: e.clientX,
    y: e.clientY,
    bizKey: view,
  };
  e.preventDefault();
};

//高度
const maxHeight = ref(600)
const updateMaxHeight = () => {
  maxHeight.value = document.body.scrollHeight;
};
onMounted(() => {
  if (viewScrollbar.value) {
    viewScrollbar.value.wrapRef.addEventListener('scroll', handleScroll);
  }
  getList({})
  updateMaxHeight();
  window.addEventListener('resize', updateMaxHeight);
});
onBeforeUnmount(() => {
  if (viewScrollbar.value) {
    viewScrollbar.value.wrapRef.removeEventListener('scroll', handleScroll);
  }
  window.removeEventListener('resize', updateMaxHeight);
});

</script>
<style  lang="scss">
.container {
  width: 100%;
  height: 100vh; /* 或者你想要的高度 */
  border: 1px solid #000; /* 可选，用于查看边界 */
  overflow: hidden; /* 确保内容不会溢出 */
  position: relative; /* 使iframe的绝对定位相对于这个div */
}
.container iframe {
  width: 100%;
  height: 100%;
  border: none; /* 去掉iframe的边框 */
  position: absolute; /* 使iframe绝对定位 */
  top: 0;
  left: 0;
}
.file-box {
  position: relative;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  padding: 5px;
  overflow: hidden;
  color: #8c939d;
  text-align: center;
  cursor: pointer;
  .upload {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 250px;
    height: 250px;
    border: 1px dashed #dcdfe6;
    border-radius: 6px;
    padding: 5px;
    .icon {
      span {
        font-size: 14px;
      }
    }
    &:hover {
      color: #409eff;
      border-color: #409eff;
    }
  }
}
.image-card {
  margin: 10px;
  height: auto;
  border-radius: 10px;
  position: relative;
  display: flex;
  flex-direction: column;
}
</style>
